package com.kaishengit.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.transaction.annotation.Transactional;

import com.kaishengit.dao.AddressDao;
import com.kaishengit.dao.ContactDao;
import com.kaishengit.dao.EmailDao;
import com.kaishengit.dao.PhoneDao;
import com.kaishengit.dao.TagDao;
import com.kaishengit.dao.core.Page;
import com.kaishengit.pojo.Address;
import com.kaishengit.pojo.Contact;
import com.kaishengit.pojo.Email;
import com.kaishengit.pojo.Phone;
import com.kaishengit.pojo.Tag;
import com.kaishengit.pojo.User;
@Transactional
public class ContactService {
	private ContactDao contactDao;
	private PhoneDao phoneDao;
	private EmailDao emailDao;
	private AddressDao addressDao;
	private TagDao tagDao;

	/**
	 * 根据首字母等进行联系人搜索
	 * */
	public List<Contact> searchContact(String q_pinyin,User user) {
		if(q_pinyin == null){
			return null;
		}else{
			return contactDao.search(q_pinyin,user);
		}
	}
	
	/**
	 * 根据userid查询所对应的联系人并进行分页
	 * */
	public 	Page<Contact> findForPage(User user,Page<Contact> page){
		return contactDao.findByPage("user", user, page);
	}
	
	//根据搜索框去搜索联系人
	public Page<Contact> findBySousuo(User user, String sousuo,Page<Contact> page) {
		return contactDao.findByTwoProperty("user",user,"type",sousuo,page);
	}
	
	//根据联系人的名字去搜公司
	public Contact findByCompanyName(String name) {
		return contactDao.findByUnique("name", name);
	}
	
	//保存联系人
	public void save(Contact contact,User user, String[] tel, String[] teltype,
			String[] email, String[] emailtype, String[] address, String[] addresstype, String groupview, String personview) {
		//如果保存的为联系人：
		if("person".equals(contact.getType())){
			Contact con=findByCompanyName(contact.getCompany());//判断是否已存在该公司
			if(con==null){
				//将公司保存进数据库
				Contact c=new Contact();
				c.setName(contact.getCompany());
				c.setType("company");
				c.setUser(user);
				contactDao.save(c);
				//获得公司的id
				contact.setCompany_id(c.getId());
			}else{
				contact.setCompany_id(con.getId());
			}
		}
		
		//可见性中select的设置
		if("meandgroup".equals(contact.getViews())){
			contact.setGroupview(groupview);
		}
		if("meandother".equals(contact.getViews())){
			contact.setPersonview(personview);
		}
		String name=contact.getName().substring(0, 1);
		contact.setFirstname(name);//获得firstname
		contactDao.save(contact);
		
		//保存电话,地址,邮箱：
		//System.out.println(contact.getId()+"*************");
		//电话
		if(tel.length!=0){
			for(int i=0;i<tel.length;i++){
				if(tel[i]!=null){
					Phone phone=new Phone();
					phone.setNum(tel[i]);
					phone.setType(teltype[i]);
					phone.setContact(contact);
					phoneDao.save(phone);
				}
			}
		}
			
		//邮箱
		if(email.length!=0){
			for(int j=0;j<email.length;j++){
				if(email[j]!=null){
					Email em=new Email();
					em.setEmail(email[j]);
					em.setType(emailtype[j]);
					em.setContact(contact);
					emailDao.save(em);
				}
			}
		}
			
			//地址
		if(address.length!=0){
			for(int m=0;m<address.length;m++){
				if(address[m]!=null){
					Address add=new Address();
					add.setAddress(address[m]);
					add.setType(addresstype[m]);
					add.setContact(contact);
					addressDao.save(add);
				}
			}
		}
			
		
	}
	//根据id查找联系人
	public Contact findById(String id) {
		return contactDao.get(id);
	}
	//在单个联系人页面保存标签
	public void save(String id, User user, String addtag) {
		Contact c=findById(id);
		Tag t=new Tag();
		t.setContent(addtag);
		t.setContact(c);
		t.setUser(user);
		t.setFirstword(addtag.substring(0, 1));
		tagDao.save(t);
	}
	//当全选时保存标签
	public void save(Page<Contact> contactlist, User user, String addtag) {
		for(Contact c:contactlist.getResult()){
			Tag t=new Tag();
			t.setContent(addtag);
			t.setContact(c);
			t.setUser(user);
			t.setFirstword(addtag.substring(0, 1));
			tagDao.save(t);
		}
		System.out.println("成功!");
	}
	//当不是全选时保存标签
	public void save(String[] mecheck, User user, String addtag) {
		System.out.println(addtag+"$$$$$$$$$$$$$");
		for(String str:mecheck){
			System.out.println(str+"$$$$$$$$$$$$$");
			Contact con=findById(str);
			Tag t=new Tag();
			t.setContent(addtag);
			t.setContact(con);
			t.setUser(user);
			t.setFirstword(addtag.substring(0, 1));
			tagDao.save(t);
		}
	}
	
	/**
	 * 修改联系人
	 * @param id 
	 * @param addressid 
	 * @param telid 
	 * @param emailid 
	 * */
	public void update(User user,String id, Contact contact, String[] tel, String[] teltype,String[] telid,
			String[] email, String[] emailtype,String[] emailid, String[] address,
			String[] addresstype,String[] addressid, String groupview, String personview) {
			System.out.println(contact.getId()+"********************");
			System.out.println(contact.getCompany());
			Contact c=findById(id);
			c.setName(contact.getName());
			Contact con=findByCompanyName(contact.getCompany());//判断是否已存在该公司
			if(con==null){
				//将公司保存进数据库
				Contact c2=new Contact();
				c2.setName(contact.getCompany());
				c2.setType("company");
				c2.setUser(user);
				contactDao.save(c2);
				//获得公司的id
				c.setCompany_id(c2.getId());
			}
			c.setCompany(contact.getCompany());
			c.setTitle(contact.getTitle());
			c.setMainpage(contact.getMainpage());
			if("meandgroup".equals(contact.getViews())){
				c.setGroupview(contact.getGroupview());
			}
			if("meandother".equals(contact.getViews())){
				c.setPersonview(contact.getPersonview());
			}
			String name=contact.getName().substring(0, 1);
			c.setFirstname(name);//获得firstname
			contactDao.save(c);
		if(tel.length!=0){
				for(int i=0;i<tel.length;i++){
					if(tel[i]!=null){
						System.out.println(tel.length);
						System.out.println(telid);
						if(telid==null){
							Phone p=new Phone();
							p.setNum(tel[i]);
							p.setType(teltype[i]);
							p.setContact(c);
							phoneDao.save(p);
						}else{
							int q=telid.length;
							if(i<q){
								Phone phone=phoneDao.get(telid[i]);
								phone.setNum(tel[i]);
								phone.setType(teltype[i]);
								phoneDao.save(phone);
							}else{
								Phone p=new Phone();
								p.setNum(tel[i]);
								p.setType(teltype[i]);
								p.setContact(c);
								phoneDao.save(p);
							}
						}
						
					}
				}
			}
			//邮箱
			if(email.length!=0){
				for(int j=0;j<email.length;j++){
					if(email[j]!=null){
						if(emailid==null){
							Email e=new Email();
							e.setEmail(email[j]);
							e.setType(emailtype[j]);
							e.setContact(c);
							emailDao.save(e);
						}else{
							int g=emailid.length;
							if(j<g){
								Email em=emailDao.get(emailid[j]);
								em.setEmail(email[j]);
								em.setType(emailtype[j]);
								emailDao.save(em);
							}else{
								Email e=new Email();
								e.setEmail(email[j]);
								e.setType(emailtype[j]);
								e.setContact(c);
								emailDao.save(e);
							}
						}
					}
				}
			}
			
			//地址
			if(address.length!=0){
				for(int m=0;m<address.length;m++){
					if(address[m]!=null){
						if(addressid==null){
							Address add=new Address();
							add.setAddress(address[m]);
							add.setType(addresstype[m]);
							add.setContact(c);
							addressDao.save(add);
						}else{
							int f=addressid.length;
							if(m<f){
								Address add=addressDao.get(addressid[m]);
								add.setAddress(address[m]);
								add.setType(addresstype[m]);
								addressDao.save(add);
							}else{
								Address add=new Address();
								add.setAddress(address[m]);
								add.setType(addresstype[m]);
								add.setContact(c);
								addressDao.save(add);
							}
						}
					}
				}
			}
	}
	
	public List<Contact> findAllPerson() {
		return contactDao.findAllByProperty("type", "person");
	}
	//删除联系人
	public void del(String id) {
		System.out.println(id+"********************");
		contactDao.del(id);
	}
	
	//找到所有联系人
	public List<Contact> findAll() {
		return contactDao.findAll();
	}

	//导出联系人
	//public void outcontact(User user, String outselect, String excelname, String[] selectid) {
		//重命名文件
		/*  if(excelname.equals("输入导出时文件名")){
	      	  excelname="contact_excel";
	        }
		  //获得联系人的集合
		  Page<Contact> page = new Page<Contact>();
		  Page<Contact> contactlist=new Page<Contact> ();
		  List<Contact> list;
		  if(outselect!=null){
			  contactlist=findForPage(user,page);
			  list=contactlist.getResult();
		  }else{
			  list=new ArrayList<Contact>();
			  for(String st:selectid){
					System.out.println(st);
					Contact con=findById(st);
					list.add(con);
				}
		  }
		  //导出
		  HSSFWorkbook wb=new HSSFWorkbook();
	       
	       //生成一个表格
	       HSSFSheet sheet=wb.createSheet("我的联系人");
	       int m=list.size()+1;
	       for(int r=0;r<m;r++){
	       	//生成一个列
	    	   if(r==0){
	    		   HSSFRow row=sheet.createRow(r);
	               //填充单元格
	               String str[]=new String[4];
	               str[0]="姓名";
	               str[1]="公司";
	               str[2]="职位";
	               str[3]="主页";
	               		
	               for(short i=0;i<4;i++){
	                   //声明一个单元格
	                   @SuppressWarnings("deprecation")
						HSSFCell cell=row.createCell(i);
	                   //设置单元格的字符值
	                   cell.setCellValue(new HSSFRichTextString(str[i]));
	               }
	    	   }else{
	    		   HSSFRow row=sheet.createRow(r);
	               //填充单元格
	    		   Contact c=list.get(r-1);
	               String str[]=new String[4];
	               str[0]=c.getName();
	               str[1]=c.getCompany();
	               str[2]=c.getTitle();
	               str[3]=c.getMainpage();
	               		
	               for(short i=0;i<4;i++){
	                   //声明一个单元格
	                   @SuppressWarnings("deprecation")
						HSSFCell cell=row.createCell(i);
	                   //设置单元格的字符值
	                   cell.setCellValue(new HSSFRichTextString(str[i]));
	               }
	    	   }
	       }*/
	//导出excel表格：
		public void out(List<Contact> list){
			 //声明一个工作薄
	       HSSFWorkbook wb=new HSSFWorkbook();
	     
	       //生成一个表格
	       HSSFSheet sheet=wb.createSheet("我的联系人");
	       int m=list.size()+1;
	       for(int r=0;r<m;r++){
	       	//生成一个列
	    	   if(r==0){
	    		   HSSFRow row=sheet.createRow(r);
	               //填充单元格
	               String str[]=new String[4];
	               str[0]="姓名";
	               str[1]="公司";
	               str[2]="职位";
	               str[3]="主页";
	               		
	               for(short i=0;i<4;i++){
	                   //声明一个单元格
	                   @SuppressWarnings("deprecation")
						HSSFCell cell=row.createCell(i);
	                   //设置单元格的字符值
	                   cell.setCellValue(new HSSFRichTextString(str[i]));
	               }
	    	   }else{
	    		   HSSFRow row=sheet.createRow(r);
	               //填充单元格
	    		   Contact c=list.get(r-1);
	               String str[]=new String[4];
	               str[0]=c.getName();
	               str[1]=c.getCompany();
	               str[2]=c.getTitle();
	               str[3]=c.getMainpage();
	               		
	               for(short i=0;i<4;i++){
	                   //声明一个单元格
	                   @SuppressWarnings("deprecation")
						HSSFCell cell=row.createCell(i);
	                   //设置单元格的字符值
	                   cell.setCellValue(new HSSFRichTextString(str[i]));
	               }
	    	   }
	       		
	       }
	     
	       
	       FileOutputStream fout;
			try {
				fout = new FileOutputStream("c:/mycontact.xls");
				 //输出到文件
		        wb.write(fout);
		        fout.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
	      
		}

	
	//导入联系人
	public List<Contact> incontact(String filename){
			System.out.println(filename+"***************");
			//filename=filename.substring(filename.lastIndexOf("\"));
            FileInputStream is = null;
			try {
				is = new FileInputStream(new File("c:/contacts.xls"));
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}  
            HSSFWorkbook wb = null;
			try {
				wb = new HSSFWorkbook(is);
			} catch (IOException e) {
				e.printStackTrace();
			}  
              
            HSSFSheet childSheet = wb.getSheetAt(0);  
            int rowNum = childSheet.getLastRowNum(); 
            //行循环
            List<Contact> list=new ArrayList<Contact>();
            for(int j=1;j<rowNum+1;j++)  
            {  
                HSSFRow row = childSheet.getRow(j);
                if(row!=null){
                	 int cellNum=row.getLastCellNum();
                     //行中的列循环
                	 Contact c=new Contact();
                	 String str[]=new String[4];
                     for(int k=0;k<cellNum;k++)  
                     {  
                    	 String st=row.getCell(k).toString();
                    	 if(k<4){
                    		 if(st!=""){
                    			str[k]=st;
                    		 }else{
                    			str[k]="null";
                    		 }
                    	 }
                     } 
                     c.setName(str[0]);
                     c.setCompany(str[1]);
                     c.setTitle(str[2]);
                     c.setMainpage(str[3]);
                     list.add(c);
                }   
            } 
        
       
		 return list;
	}
	
	//set
	public void setContactDao(ContactDao contactDao){
		this.contactDao = contactDao;
	}
	public void setPhoneDao(PhoneDao phoneDao) {
		this.phoneDao = phoneDao;
	}

	public void setEmailDao(EmailDao emailDao) {
		this.emailDao = emailDao;
	}

	public void setAddressDao(AddressDao addressDao) {
		this.addressDao = addressDao;
	}

	public void setTagDao(TagDao tagDao) {
		this.tagDao = tagDao;
	}

	

	
	
	
	

	

	

	

	

	

	

	
	
	


}
